package org.jeecgframework.web.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.controller.ZyInspectionPlanController;
import org.jeecgframework.web.service.ZyTimeTaskCheckReportService;
import org.jeecgframework.web.system.pojo.base.ZyEmValidaRuleEntity;
import org.jeecgframework.web.system.pojo.base.ZyInspectionPlanEntity;
import org.jeecgframework.web.system.pojo.base.ZyInspectionReportEntity;
import org.jeecgframework.web.system.pojo.base.ZyReportExceptionsEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMessage;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @ClassName：ZyTimeTaskCheckReportServiceImpl.java
 * @Description：
 * @author：LeiYoung
 * @version：V1.0
 * @Date：2016年10月9日 下午1:56:34
 */
@Service(value = "zyTimeTaskCheckReportService")
@Transactional
public class ZyTimeTaskCheckReportServiceImpl extends CommonServiceImpl implements ZyTimeTaskCheckReportService {

	private static final Logger logger = Logger.getLogger(ZyTimeTaskCheckReportServiceImpl.class);
	 
	@Autowired
	public SystemService systemService;

	@Override
	public void zyCheckInspectionPlanReport() {
		System.out.println("定时任务开始-检查巡检报告中的异常项");
		try {
			List<ZyInspectionReportEntity> zyReports = systemService.findHql("from ZyInspectionReportEntity where isChecked is null OR isChecked = ?", false);
			// 根据是否已经检查过字段查询全部未检查巡检报告
			System.out.println("一共：" + zyReports.size() + "个待检查报告");
			int count = 0;
			for (ZyInspectionReportEntity zyIr : zyReports) {
				System.out.println("开始检查第" + count + "个...");
				count++;
				// 根据巡检计划ID查询巡检计划
				ZyInspectionPlanEntity zyIp = super.get(ZyInspectionPlanEntity.class, zyIr.getInspectionPlanId());
				if (zyIp == null) {
					continue;
				}
				if (zyIp.getEquipmentSpare() == null) {
					continue;
				}
				if (zyIp.getEquipmentSpare().getType() == null) {
					continue;
				}
				if (!StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE.equals(zyIp.getState())) {
					continue;
				}
				// 巡检报告异常
				ZyReportExceptionsEntity zree = new ZyReportExceptionsEntity();
				List<ZyEmValidaRuleEntity> zyEmValidataRules = super.findByProperty(ZyEmValidaRuleEntity.class, "equipmentTypeId", zyIp.getEquipmentSpare().getType().getId());
				boolean save = false;
				int rCount = 0;
				if (null != zyEmValidataRules) {
					for (ZyEmValidaRuleEntity zyEmRule : zyEmValidataRules) {
					System.out.println("开始检查第"+count+"个第"+rCount+"项");
					rCount++;
					// 最大值
					Double max = zyEmRule.getMax();
					// 最小值
					Double min = zyEmRule.getMin();
					// 维护项目
					String maintainProject = zyEmRule.getMaintainProject();
					switch (maintainProject) {
						/** 维护项目 是 温度 */
						case StaticValue.DIC_MAINTAIN_PROJECT_TEMPERATURE:
							if (zyIr.getYtRmTemperature() != null && StringUtil.isFloatNumeric(zyIr.getYtRmTemperature())) {
								// 机房工作环境温度不为空 并且 机房工作环境温度为Double类型
								// 转化机房工作环境温度为Double类型
								Double ytRmTemperature = Double.valueOf(zyIr.getYtRmTemperature());
								if (max != null && min == null) {
									if (max.compareTo(ytRmTemperature) < 0) {
										save = true;
										zree.setIsTemperatureEx(true);
										zree.setTemperatureExVal(ytRmTemperature);
									}
								} else if (max == null && min != null) {
									if (min.compareTo(ytRmTemperature) > 0) {
										save = true;
										zree.setIsTemperatureEx(true);
										zree.setTemperatureExVal(ytRmTemperature);
									}
								} else if (max != null && min != null) {
									if (max.compareTo(ytRmTemperature) < 0 || min.compareTo(ytRmTemperature) > 0) {
										save = true;
										zree.setIsTemperatureEx(true);
										zree.setTemperatureExVal(ytRmTemperature);
									}
								}
							}
						break;
					/** 维护项目 是 湿度 */
					case StaticValue.DIC_MAINTAIN_PROJECT_HUMIDITY:
						if (null != zyIr.getYtRmHumidity() && StringUtil.isFloatNumeric(zyIr.getYtRmHumidity())) {
							// 转化机房工作环境湿度为Double类型
							Double ytRmHumidity = Double.valueOf(zyIr.getYtRmHumidity());
							if (max != null && min == null) {
								if (max.compareTo(ytRmHumidity) < 0) {
									save = true;
									zree.setIsHumidityEx(true);
									zree.setHumidityExVal(ytRmHumidity);
								}
							} else if (max == null && min != null) {
								if (min.compareTo(ytRmHumidity) > 0) {
									save = true;
									zree.setIsHumidityEx(true);
									zree.setHumidityExVal(ytRmHumidity);
								}
							} else if (max != null && min != null) {
								if (max.compareTo(ytRmHumidity) < 0 || min.compareTo(ytRmHumidity) > 0) {
									save = true;
									zree.setIsHumidityEx(true);
									zree.setHumidityExVal(ytRmHumidity);
								}
							}
						}
						break;
					/** 维护项目 是 冷却液压力 */
					case StaticValue.DIC_MAINTAIN_PROJECT_COOLANTPRESSURE:
						if (null != zyIr.getLqCoolantH() && StringUtil.isFloatNumeric(zyIr.getLqCoolantH())) {
							// 转化冷却液压力为Double类型
							Double lqCoolantH = Double.valueOf(zyIr.getLqCoolantH());
							if (max != null && min == null) {
								if (max.compareTo(lqCoolantH) < 0) {
									save = true;
									zree.setIsCoolantPressureEx(true);
									zree.setCoolantPressureExVal(lqCoolantH);
								}
							} else if (max == null && min != null) {
								if (min.compareTo(lqCoolantH) > 0) {
									save = true;
									zree.setIsCoolantPressureEx(true);
									zree.setCoolantPressureExVal(lqCoolantH);
								}
							} else if (max != null && min != null) {
								if (max.compareTo(lqCoolantH) < 0 || min.compareTo(lqCoolantH) > 0) {
									save = true;
									zree.setIsCoolantPressureEx(true);
									zree.setCoolantPressureExVal(lqCoolantH);
								}
							}
						}
						break;
					/** 维护项目 是 冷却液液面高度 */
					case StaticValue.DIC_MAINTAIN_PROJECT_COOLANTHEIGHT:
						if (null != zyIr.getLqCoolantLiquidH() && StringUtil.isFloatNumeric(zyIr.getLqCoolantLiquidH())) {
							// 转化冷却液液面高度为Double类型
							Double lqCoolantLiquidH = Double.valueOf(zyIr.getLqCoolantLiquidH());
							if (max != null && min == null) {
								if (max.compareTo(lqCoolantLiquidH) < 0) {
									save = true;
									zree.setIsCoolantHeightEx(true);
									zree.setCoolantHeightExVal(lqCoolantLiquidH);
								}
							} else if (max == null && min != null) {
								if (min.compareTo(lqCoolantLiquidH) > 0) {
									save = true;
									zree.setIsCoolantHeightEx(true);
									zree.setCoolantHeightExVal(lqCoolantLiquidH);
								}
							} else if (max != null && min != null) {
								if (max.compareTo(lqCoolantLiquidH) < 0 || min.compareTo(lqCoolantLiquidH) > 0) {
									save = true;
									zree.setIsCoolantHeightEx(true);
									zree.setCoolantHeightExVal(lqCoolantLiquidH);
								}
							}						
						}
						break;
					/** 维护项目 是 亮度 */
					case StaticValue.DIC_MAINTAIN_PROJECT_BRIGHTNESS:
						if (null != zyIr.getYxLightCenter() && StringUtil.isFloatNumeric(zyIr.getYxLightCenter())) {
							// 转化机房工作环境亮度为Double类型
							Double yxLightC = Double.valueOf(zyIr.getYxLightCenter());
							if (max != null && min == null) {
								if (max.compareTo(yxLightC) < 0) {
									save = true;
									zree.setIsBrightnessEx(true);
									zree.setBrightnessExVal(yxLightC);
								}
							} else if (max == null && min != null) {
								if (min.compareTo(yxLightC) > 0) {
									save = true;
									zree.setIsBrightnessEx(true);
									zree.setBrightnessExVal(yxLightC);
								}
							} else if (max != null && min != null) {
								if (max.compareTo(yxLightC) < 0 || min.compareTo(yxLightC) > 0) {
									save = true;
									zree.setIsBrightnessEx(true);
									zree.setBrightnessExVal(yxLightC);
								}
							}
						}
						break;
					/** 维护项目 是 风速 */
					case StaticValue.DIC_MAINTAIN_PROJECT_WINDSPEED:
						if (null != zyIr.getLqVentSpeed() && StringUtil.isFloatNumeric(zyIr.getLqVentSpeed())) {
							// 转化机房工作环境风速为Double类型
							Double lqVentSpeed = Double.valueOf(zyIr.getLqVentSpeed());
							if (max != null && min == null) {
								if (max.compareTo(lqVentSpeed) < 0) {
									save = true;
									zree.setIsWindSpeedEx(true);
									zree.setWindSpeedExVal(lqVentSpeed);
								}
							} else if (max == null && min != null) {
								if (min.compareTo(lqVentSpeed) > 0) {
									save = true;
									zree.setIsWindSpeedEx(true);
									zree.setWindSpeedExVal(lqVentSpeed);
								}
							} else if (max != null && min != null) {
								if (max.compareTo(lqVentSpeed) < 0 || min.compareTo(lqVentSpeed) > 0) {
									save = true;
									zree.setIsWindSpeedEx(true);
									zree.setWindSpeedExVal(lqVentSpeed);
								}
							}
						}
						break;
					/** 维护项目 是 零地电压 */
					case StaticValue.DIC_MAINTAIN_PROJECT_ZEROGROUNDVOLTAGE:
						if (null != zyIr.getXlZeroVoltage() && StringUtil.isFloatNumeric(zyIr.getXlZeroVoltage())) {
							// 转化机房工作环境零地电压为Double类型
							Double xlZeroVoltage = Double.valueOf(zyIr.getXlZeroVoltage());
							if (max != null && min == null) {
								if (max.compareTo(xlZeroVoltage) < 0) {
									save = true;
									zree.setIsZeroGroundVoltageEx(true);
									zree.setZeroGroundVoltageExVal(xlZeroVoltage);
								}
							} else if (max == null && min != null) {
								if (min.compareTo(xlZeroVoltage) > 0) {
									save = true;
									zree.setIsZeroGroundVoltageEx(true);
									zree.setZeroGroundVoltageExVal(xlZeroVoltage);
								}
							} else if (max != null && min != null) {
								if (max.compareTo(xlZeroVoltage) < 0 || min.compareTo(xlZeroVoltage) > 0) {
									save = true;
									zree.setIsZeroGroundVoltageEx(true);
									zree.setZeroGroundVoltageExVal(xlZeroVoltage);
								}
							}
						}
						break;
					/** 培训人数 */
					case StaticValue.DIC_MAINTAIN_PROJECT_TRAINING_NUM:
						if (zyIr.getTrainingNum() != null && StringUtil.isInteger(zyIr.getTrainingNum())) {
							//培训人数不符合规定
							Double trainingNum = Double.valueOf(zyIr.getTrainingNum());
							if (max != null && min == null) {
								if (max.compareTo(trainingNum) < 0) {
									save = true;
									zree.setIsTrainingNumEx(true);
									zree.setTrainingNumExVal(trainingNum);
								}
							} else if (max == null && min != null) {
								if (min.compareTo(trainingNum) > 0) {
									save = true;
									zree.setIsTrainingNumEx(true);
									zree.setTrainingNumExVal(trainingNum);
								}
							} else if (max != null && min != null) {
								if (max.compareTo(trainingNum) < 0 || min.compareTo(trainingNum) > 0) {
									save = true;
									zree.setIsTrainingNumEx(true);
									zree.setTrainingNumExVal(trainingNum);
								}
							}
						}
						break;
					default:
						continue;
					}
				}
				if (save) {
					Calendar cal = Calendar.getInstance();
					cal.setTime(zyIp.getEndTime());
					zree.setYear(cal.get(Calendar.YEAR));
					zree.setMonth(cal.get(Calendar.MONTH) + 1);
					zree.setReportId(zyIr.getId());
					super.save(zree);
				}
				zyIr.setIsChecked(true);
				super.saveOrUpdate(zyIr);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("巡检报告异常项检查完毕");
	}

	@Override
	public void timeTaskOfCheckPlanOfEngineer() {
		System.out.println("[超时任务提醒 + 次日巡检任务提醒] 定时任务开始运行...["+DateUtils.date2Str(new Date(),DateUtils.datetimeFormat)+"]");
		
		/** 超时任务提醒：第三方工程师接受的巡检计划中在指定的预约上门时间48小时后还未提交巡检报告的巡检计划，本系统将给工程师发送一条短信 */
		StringBuffer sql = new StringBuffer();
		
		sql.append(" select");
		sql.append(" count(1) as total,");
		sql.append(" eg.name as engineerName, eg.cellphone");
		sql.append(" from");
		sql.append(" zy_inspection_plan ip");
		sql.append(" left join zy_inspection_report ir on ir.inspection_plan_id = ip.id");
		sql.append(" left join zy_engineer eg on eg.id = ip.engineer");
		sql.append(" where");
		sql.append(" ip.state = '").append(StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED).append("'");
		sql.append(" and isnull(ir.id)");
		sql.append(" and ip.engineer_order_time is not null");
		sql.append(" and timestampdiff(hour ,ip.engineer_order_time,now()) > 48");
		sql.append(" group by");
		sql.append(" ip.engineer");
		List<Map<String, Object>> mapList = super.findForJdbc(sql.toString());
		if (null != mapList && mapList.size() > 0) {
			for (Map<String, Object> map : mapList) {
				try {
					// 发送短信
					Map<String, Object> paraMap = new HashMap<String, Object>();
					paraMap.put("engineerName", map.get("engineername").toString());
					paraMap.put("total", map.get("total").toString());
					SendMessage.sendSMSFTL(map.get("cellphone").toString(), "message_taskOverTime.ftl", paraMap, systemService);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		/** 次日巡检任务提醒：本人接受的巡检计划中预约上门时间为第二天还未提交巡检报告的巡检计划，系统将给工程师发送一条短信 */
		sql = new StringBuffer();
		sql.append(" SELECT ");
		sql.append(" 	count(1) AS total, ");
		sql.append(" 	eg.`name` AS engineerName, cm.`name` AS cinemaName, eg.cellphone ");
		sql.append(" FROM ");
		sql.append(" 	zy_inspection_plan ip ");
		sql.append(" LEFT JOIN zy_engineer eg ON eg.id = ip.engineer ");
		sql.append(" LEFT JOIN zy_inspection_report ir ON ir.inspection_plan_id = ip.id ");
		sql.append(" LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id ");
		sql.append(" LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id ");
		sql.append(" WHERE ");
		sql.append(" 	ip.state = '").append(StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED).append("' ");
		sql.append(" AND ISNULL(ir.id) ");
		sql.append(" AND ip.engineer_order_time IS NOT NULL ");
		sql.append(" AND TIMESTAMPDIFF(DAY ,ip.engineer_order_time,CURDATE()) = 1");
		sql.append(" GROUP BY ");
		sql.append(" 	ip.engineer ");
		mapList = super.findForJdbc(sql.toString());
		
		if (null != mapList && mapList.size() > 0) {
			for (Map<String, Object> map : mapList) {
				try {
					// 发送短信
					Map<String, Object> paraMap = new HashMap<String, Object>();
					paraMap.put("engineerName", map.get("engineername").toString());
					paraMap.put("cinemaName", map.get("cinemaname").toString());
					SendMessage.sendSMSFTL(map.get("cellphone").toString(), "message_taskTomorrow.ftl", paraMap, systemService);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		System.out.println("结束 - [超时任务提醒 + 次日巡检任务提醒]["+DateUtils.date2Str(new Date(),DateUtils.datetimeFormat)+"]");
	}

}
